//websocket对象
var ws = null;
//本地视频流
var localStream;
//远端视频流
var remoteStream;
//本机RtcPeerConnection
var pc = null;

var offer = null;
var answer = null;


//初始化方法
$(document).ready(function () {
    //初始化MyTab事件
    init_mytab();

    //初始化所有快捷键
    //init_hotkeys();

    //初始化锁屏框
    init_lock_dialog();

    //初始化websocket
    init_socket();
});

//初始化锁屏框
function init_lock_dialog() {

    //主页面判读是否锁屏
    var isLock =$("#isLock").val();
    if ("1" == isLock) {
        $('#lockdialog_info').val('');
        $("#lockdialog").modal("show");
    }

    //解锁密码框回车事件-调用解锁
    $("#lockdialog_info").keydown(function (e) {
        if (e.keyCode == 13) {
            unlock();
        }
    });

    //锁屏前
    $('#lockdialog').on('show.bs.modal', function (event) {
        //alert('show');
    });

    //解锁前
    $('#lockdialog').on('hidePrevented.bs.modal', function (event) {
        //alert('hidePrevented');
    });
}

/**
 * 初始化所有快捷键
 */
function init_hotkeys() {
    //$(document).bind('keydown', KdDescribeEvent);
    //$(document).bind('keypress', KpDescribeEvent);

    /*   function KdDescribeEvent(event){
          console.log('which:'+event.which);
          console.log('shiftKey:'+event.shiftKey);
          console.log('ctrlKey:'+event.ctrlKey);
          console.log('altKey:'+event.altKey);
      } */
    /* function KpDescribeEvent(event){
        console.log('which:'+event.which);
        console.log('shiftKey:'+event.shiftKey);
        console.log('ctrlKey:'+event.ctrlKey);
        console.log('altKey:'+event.altKey);
    } */

    //启动表单管理
    /* jQuery(document).bind('keypress', 'f1',function (evt){
        addTab('表单管理','list?tableId=z_form','fa fa-window-restore','from_system');
    }); */

}

/**
 * 初始化MyTab事件
 */
function init_mytab() {

    $('#myTab').tabs({
        //菜单选中事件
        onSelect:function (title, index) {
            var id = $('#myTab').tabs('getSelected').panel('options').id;
            //计算面包屑导航
            CountBreadcrumb(id);
        },
        //监听右键事件，创建右键菜单
        onContextMenu: function (e, title, index) {
            e.preventDefault();
            if (index >= 0) {
                $('#my_tab_menu').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                }).data("tabTitle", title);
            }
        },
        //添加关闭前事件
        onBeforeClose: function (title, index) {
            var id = $('#myTab').tabs('getSelected').panel('options').id;
            var url = $('#iframe_' + id).attr("src");
            //清除当前表单Cookie
            removeCookie(url);
        }
    });

    //右键菜单点击事件
    $("#my_tab_menu").menu({
        onClick: function (item) {
            //刷新当前页面
            if (item.name == 'tab_refresh') {
                var tab = $('#myTab').tabs('getSelected');
                var tabindex = $('#myTab').tabs('getTabIndex', tab);
                if (tabindex > 0) {
                    tab.find('iframe')[0].contentWindow.location.reload(true);
                } else {
                    //刷新主页
                    $('#index_iframe').attr('src', $('#index_iframe').attr('src'));
                }
            }
            //关闭其它
            if (item.name == 'tab_close_other_all') {
                var tablist = $('#myTab').tabs('tabs');
                var tab = $('#myTab').tabs('getSelected');
                for (var i = tablist.length - 1; i > 0; i--) {
                    if (tab != tablist[i]) {
                        $('#myTab').tabs('close', i);
                    }
                }
            }
            //关闭全部
            if (item.name == 'tab_close_all') {
                var tablist = $('#myTab').tabs('tabs');
                for (var i = tablist.length - 1; i > 0; i--) {
                    $('#myTab').tabs('close', i);
                }
            }
        }
    });
}


/**
 * 菜单事件方法
 */
function MenuTreeSelect(o) {
    addTab(o.text, o.url, o.iconCls, o.zid);
}

/**
 * 手机端打开菜单方法
 */
function MenuTreeSelectMobile(o) {
    window.location.href = o.url;
}

/**
 * 生成面包学
 * @param zid
 * @constructor
 */
function CountBreadcrumb(zid){
    $('#BreadcrumbBox').empty();
    var m = getMenuinfo(zid);
    if(isNotNull(m) && isNotNull(m.obj)){
        var ma = m.obj.split(",");
        for (var i = 0; i < ma.length; i++) {
            var pm = getMenuinfo(ma[i]);
            if(isNotNull(pm)){
                $('#BreadcrumbBox').prepend('<li class="breadcrumb-item">'+pm.name+'</li>');
            }
        }
    }
}

//根据菜单ID获取菜单对象
function getMenuinfo(zid){
    var rm;
    var list = $("#all_menu").val();
    var listjson = $.parseJSON(list);
    for (var i = 0; i < listjson.length; i++) {
        var m = listjson[i];
        if(m.zid == zid){
            rm = m;
            break;
        }
    }
    return rm;
}

/**
 * 创建Tab
 * @param number
 * @param title
 * @param url
 */
function addTab(tab_title, url, iconcls, zid) {
    if (url != '#') {
        if (isNotNull(url) && isNotNull(tab_title) && url != '#') {

            //判读是否是移动端
            if (isMobile()) {
                //mobile
                window.location.href = url;
            } else {

                //生成面包屑导航
                CountBreadcrumb(zid,$("#user_all_menu_list").val());

                //PC
                if (!$('#myTab').tabs('exists', tab_title)) {
                    $('#myTab').tabs('add', {
                        id: zid,
                        title: tab_title,
                        content: '<div style="position:relative;width:100%;height:100%;">'
                            + '<div id="box_' + zid + '" style="position:absolute;left:0;top:0;width:100%;height:100%;" class="d-flex align-items-center d-flex justify-content-center">'
                            + '<img alt="" src="/img/system/loading.gif" width="120px" height="120px"/>'
                            + '</div>'
                            + '<iframe id="iframe_' + zid + '" name="mainFrame" scrolling="auto" frameborder="0"  src="' + url + '" style="position:absolute;left:0;top:0;width:100%;height:100%;"></iframe>'
                            + '</div>',
                        closable: true,
                        iconCls: iconcls
                    });
                } else {
                    $('#myTab').tabs('select', tab_title);
                }
            }

        } else {
            alertErrorMessager("菜单参数缺失，无法打开功能。tab_title：" + tab_title + " | URL:" + url + " |iconcls:" + iconcls);
        }
    }
}

//锁屏
function locking() {
    var userid = $("#now_user_zid").val();
    $.ajax({
        type: "get",
        url: 'user_locking',
        data: {zid: userid},
        success: function (data) {
            if (data.code == 'SUCCESS') {
                $('#lockdialog_info').val('');
                $("#lockdialog").modal("show");
            } else {
                alertErrorMessager('' + data.msg);
            }
        },
        error: function (data) {
            alertErrorMessager('ajax错误：' + JSON.stringify(data));
        }
    });
}


//解锁
function unlock() {
    var password = $('#lockdialog_info').val();
    if (isNotNull(password)) {
        var userid = $("#now_user_zid").val();
        $.ajax({
            type: "get",
            url: 'user_unlock',
            data: {zid: userid, password: password},
            success: function (data) {
                if (data.code == 'SUCCESS') {
                    $("#lockdialog").modal("hide");
                } else {
                    $('#lockdialog_span').text('' + data.msg);
                }
            },
            error: function (data) {
                $('#lockdialog_span').text('ajax错误：' + JSON.stringify(data));
            }
        });
    } else {
        $('#lockdialog_span').text('请输入解锁密码');
    }
}

/**
 * 弹出html框
 */
function alertHtmlBox(zalert_title,msg){
    $("#zalert_head").removeClass("modal-xl");
    $("#zalert_title").html(zalert_title);
    $("#zalert_info").html(msg);
    $("#zalert").modal("show");
}

/**
 * 提示信息
 */
function alertMessager(msg) {
    // $("#zalert_head").removeClass("modal-xl");
    // $("#zalert_title").html("提示");
    // $("#zalert_info").html(msg);
    // $("#zalert").modal("show");
    $.messager.show({
        title: '信息提示',
        msg: msg,
        timeout: 3000,
        showType: 'slide'
    });

    //播放提示音
    alert_audio();

}

/**
 * 播放提示音
 */
function alert_audio(){
    var audio = document.getElementById('alert_audio');
    if(audio!==null){
        //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
        if(audio.paused)                     {
            audio.play();//audio.play();// 这个就是播放
        }else{
            audio.pause();// 这个就是暂停
        }
    }
}


/**
 * 播放来电提示音
 */
function tel_audio(){
    var audio = document.getElementById('tel_audio');
    if(audio!==null){
        //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
        if(audio.paused)                     {
            audio.play();//audio.play();// 这个就是播放
        }else{
            audio.pause();// 这个就是暂停
        }
    }
}
/**
 * 提示信息[自动关闭]
 */
function alertMessagerAutoOff(msg) {
    /* 	$('.alert').alert(msg);
        $("#zalert_head").removeClass("modal-xl");
        $("#zalert_title").html("信息提示");
        $("#zalert_info").html(msg);
        $("#zalert").modal("show");

        setTimeout(function () {
            $("#zalert").modal("hide");
        }, 1300); */


    $.messager.show({
        title: '信息提示',
        msg: msg,
        timeout: 3000,
        showType: 'slide'
    });
}

/**
 * 弹出错误提示框
 */
function alertErrorMessager(msg) {
    $("#zalert_head").removeClass("modal-xl");
    $("#zalert_title").html("警告信息");
    $("#zalert_info").html("<textarea class=\"form-control\" rows=\"30\">" + msg + "</textarea>");
    $("#zalert").modal("show");
}

/**
 * 图片展示框
 */
function alertImgWindows(imgUrl) {
    $("#zimgalert_head").addClass("modal-xl");
    $("#zimgalert_title").html("图片");
    $("#zimgalert_info").html("<img id=\"ImgWindowsId\" class=\"img-fluid rounded mx-auto d-block\" src='" + imgUrl + "'>");
    $("#imgRotate").val(0);//图片角度
    $("#zimgalert").modal("show");
}

/**
 * 左旋90度
 */
function imgWindowsTurnLeft(){
    var rotateValue = parseFloat($("#imgRotate").val());
    var baseRotateValue = parseFloat(90);
    var newRotateValue = rotateValue - baseRotateValue;
    $("#imgRotate").val(newRotateValue);
    $("#ImgWindowsId").css("transform","rotate("+$("#imgRotate").val()+"deg)");

}

/**
 * 右旋90度
 */
function imgWindowsTurnRight(){
    var rotateValue = parseFloat($("#imgRotate").val());
    var baseRotateValue = parseFloat(90);
    var newRotateValue = rotateValue + baseRotateValue;
    $("#imgRotate").val(newRotateValue);
    $("#ImgWindowsId").css("transform","rotate("+$("#imgRotate").val()+"deg)");
}

/**
 * 图片展示框,放大图片
 */
function imgWindowsEnlarge(){
    var w = $("#ImgWindowsId").width();
    $("#ImgWindowsId").width(w+80);
}

/**
 * 图片展示框,缩小图片
 */
function imgWindowsNarrow(){
    var w = $("#ImgWindowsId").width();
    $("#ImgWindowsId").width(w-80);
}

/**
 * 最大化
 */
function imgWindowsMaximum(){
    $("#ImgWindowsId").width(2000);
}

/**
 * 打开加载等待
 */
function openLoading() {
    var treeid = $('#myTab').tabs('getSelected').panel('options').id;
    $("#iframe_" + treeid).addClass('visibility');

}

/**
 * 关闭加载等待
 */
function closedLoading() {
    var treeid = $('#myTab').tabs('getSelected').panel('options').id;
    $("#iframe_" + treeid).removeClass('visibility');
}


/**
 * 更新系统缓存
 */
function LoadParameter() {
    $.ajax({
        type: "GET",
        url: 'LoadParameter',
        success: function (data) {
            if (data.code == 'SUCCESS') {
                alertMessagerAutoOff(data.msg);
            } else {
                alertErrorMessager(data.msg);
            }
        }
    });

}

//更新所有ZS节点服务系统参数
function LoadZSParameter() {
    $.ajax({
        type: "get",
        url: "zs",
        data: {serviceid: 'LoadZSParameter'},
        success: function (data) {
            if (data.code == 'SUCCESS') {
                alertMessagerAutoOff(data.data.join());
            } else {
                alertErrorMessager(data.msg);
            }
        }
    });
}


//初始化菜单数据(非移动端)
if (!isMobile()) {
    var menuTreeList = jQuery.parseJSON($("#menuTreeList").val());
}


/**
 * 重启Tomcat
 */
function RestartTomcat() {
    $.messager.confirm('信息提示', '您确定要重启Tomcat服务吗？执行完成后，请等待30秒刷新页面，查看Tomcat服务是否启动', function (r) {
        if (r) {
            $.ajax({
                type: "GET",
                url: 'RestartTomcat',
                success: function (data) {
                    if (data.code == 'SUCCESS') {
                        window.location.reload();
                    } else {
                        alertErrorMessager(data.msg);
                    }
                },
                timeout: 1000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    window.location.reload();
                }
            });
        }
    });
}

/**
 * 系统升级
 */
function AutoUpdate() {
    $.messager.confirm('信息提示', '您确定要执行系统升级吗？', function (r) {
        if (r) {
            $.ajax({
                type: "GET",
                url: 'AutoUpdate',
                success: function (data) {
                    if (data.code == 'SUCCESS') {
                        window.location.reload();
                    } else {
                        alertErrorMessager(data.msg);
                    }
                },
                timeout: 1000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    window.location.reload();
                }
            });
        }
    });
}

/**
 * 获取当前登录人ID
 * @returns {string}
 */
function getNowUserZid() {
    var userid = $("#now_user_zid").val();
    return userid;
}


/**
 * 设置全屏
 */
var isFullscreen = false;
function handleFullScreen(){
    if(isFullscreen){
        var de = document;
        if(de.exitFullscreen) {
            de.exitFullscreen();
        } else if(de.msExitFullscreen) {
            de.msExitFullscreen();
        } else if(de.mozCancelFullScreen) {
            de.mozCancelFullScreen();
        } else if(de.webkitExitFullscreen) {
            de.webkitExitFullscreen();
        }

        isFullscreen = false;
    }else{
        var de = document.documentElement;
        if (de.requestFullscreen) {
            de.requestFullscreen();
        } else if (de.msRequestFullscreen) {
            de.msRequestFullscreen();
        } else if (de.webkitRequestFullScreen) {
            de.webkitRequestFullScreen();
        } else if (de.mozRequestFullScreen) {
            de.mozRequestFullScreen();
        } else {
            alertMessager("当前浏览器不支持全屏！")
        }

        isFullscreen = true;
    }
}

//初始化websocket
function init_socket() {
    if (!window.WebSocket) {
        alertMessager('您的浏览器不支持WebSocket');
    } else {
        var isMSN = $("#isMSN").val();
        if (isMSN == 'true') {
            var serverip = $("#serverip").val();
            var isSSL = $("#isSSL").val();

            var HTTPHEAD = 'ws';
            if (isSSL == 'true') {
                HTTPHEAD = "wss";
            }
            var now_user_zid = $('#now_user_zid').val();
            var socket_server_url = HTTPHEAD + '://' + serverip + '/zsocket?userid='+now_user_zid;
            ws = new WebSocket(socket_server_url);
            //链接成功事件
            ws.onopen = function () {
                console.log(now_user_zid+"已连接websocket");
            }
            ws.onclose = function(e){
                console.log(now_user_zid+'已断开websocket');
                setTimeout('init_socket()',5000);
                init_socket();
            }
            ws.onerror = function(e){
                console.log(now_user_zid+'websocket连接出错|'+e);
                setTimeout('init_socket()',5000);
                init_socket();
            }

            //接收到信息
            ws.onmessage = function (obj) {
                var ms = $.parseJSON(obj.data);
                if ('usertouser' == ms.data.command_type) {
                    //显示消息
                    printMsg(obj.data);
                } else if ('user_on_line' == ms.data.command_type) {
                    var userid = $("#now_user_zid").val();
                    var fromuserid = ms.data.fromuserid;
                    var fromusername = decodeURIComponent(ms.data.fromusername);
                    if (userid != fromuserid) {

                        var buttonname = '';
                        var buttonid = 'message_user_' + fromuserid;
                        if (isNotNull(fromusername)) {
                            alertMessager(fromusername + " 已上线")
                            buttonname = fromusername;
                        } else {
                            alertMessager(fromuserid + " 已上线")
                            buttonname = fromuserid;
                        }
                        //console.log(fromuserid+" 上线")
                        //RefreshMessagesList();

                        if ($('#' + buttonid).length <= 0) {
                            var button_html = '<button id="message_user_' + fromuserid + '" type="button" class="btn btn-success btn-block" onclick="OpenMessageWindows(\'' + fromuserid + '\',\'' + fromusername + '\')">' + buttonname + '</button>';
                            $('#UserMessagesList').append(button_html);
                        }
                    }
                } else if ('user_off_line' == ms.data.command_type) {
                    var userid = $("#now_user_zid").val();
                    var fromuserid = ms.data.fromuserid;
                    var fromusername = ms.data.fromusername;
                    if (userid != fromuserid) {
                        if(isNotNull(fromusername)){
                            alertMessager(fromusername+" 已下线")
                        }else{
                            alertMessager(fromuserid+" 已下线")
                        }
                        //console.log(fromuserid+" 下线")
                        //RefreshMessagesList();
                        var buttonid = 'message_user_'+fromuserid;
                        $('#'+buttonid).remove();
                    }
                }else if ('audio_apply' == ms.data.command_type) {
                    //播放来电提示音
                    tel_audio();
                    printMsg(obj.data);
                }else if ('audio_close' == ms.data.command_type) {
                    call_windows_close(false);
                }else if ('audio_apply_yes' == ms.data.command_type) {
                    printMsg(obj.data);

                }else if ('audio_apply_no' == ms.data.command_type) {
                    printMsg(obj.data);
                }else if ('video_apply' == ms.data.command_type) {
                    //播放来电提示音
                    tel_audio();
                    printMsg(obj.data);
                    var userid = $("#now_user_zid").val();
                    if(userid===ms.data.touserid){
                        console.log(ms.data.fromuserid+'申请和您进行视频通话');
                    }
                }else if ('video_close' == ms.data.command_type) {
                    call_windows_close(false);
                }else if ('video_apply_yes' == ms.data.command_type) {
                    //显示信息
                    printMsg(obj.data);
                    var userid = $("#now_user_zid").val();
                    if(userid===ms.data.touserid){
                        console.log(ms.data.fromuserid+'同意和您进行视频通话,开始建立连接');
                        //创建RTCPeerConnection
                        CreateRTCPeerConnection(true,'');
                        //创建createOffer
                        createOffer(1,1,'webrtc_offer');
                    }
                }else if ('video_apply_no' == ms.data.command_type) {
                    printMsg(obj.data);
                }else if ('webrtc_offer' == ms.data.command_type) {
                    var userid = $("#now_user_zid").val();
                    if(userid===ms.data.touserid){
                        offer = JSON.parse(ms.data.msg);
                        console.log(ms.data.fromuserid+'发给您的offer信息:');
                        //console.log(offer);

                        //setRemoteDescription
                        console.log('接收Offer | 执行setRemoteDescription');
                        pc.setRemoteDescription(new RTCSessionDescription(offer));

                        //创建createOffer
                        createAnswer(1,1,'webrtc_answer');
                    }
                }else if ('webrtc_answer' == ms.data.command_type) {
                    var userid = $("#now_user_zid").val();
                    if(userid===ms.data.touserid){
                        answer = JSON.parse(ms.data.msg);
                        console.log(ms.data.fromuserid+'发给您的answer信息:');
                        //console.log(answer);

                        //setRemoteDescription
                        console.log('接收Answer | 执行setRemoteDescription');
                        pc.setRemoteDescription(new RTCSessionDescription(answer));

                    }

                }else if ('webrtc_candidate' == ms.data.command_type) {

                    var userid = $("#now_user_zid").val();
                    if(userid!=ms.data.fromuserid){
                        if(pc){
                            var ic = JSON.parse(ms.data.msg);
                            //console.log('调用webrtc_candidate')
                            //console.log(ic)
                            var candidate = new RTCIceCandidate({
                                sdpMLineIndex:ic.label,
                                candidate:ic.candidate
                            })
                            console.log("fromuser:"+ms.data.fromuserid+"发送candidate| 执行addIceCandidate");
                            pc.addIceCandidate(candidate);
                        }else{
                            console.log("fromuser:"+ms.data.fromuserid+"发送candidate| 执行addIceCandidate|RtcPeerConnection未创建");
                        }
                    }

                }else if ('system_message' == ms.data.command_type) {
                    alert(ms);
                } else if ('group_message' == ms.data.command_type) {

                } else if ('e_message' == ms.data.command_type) {
                    var e_msg = ms.data.msg;
                    alertErrorMessager(e_msg);
                }
            };
            // 关闭页面时候关闭ws
            window.addEventListener("beforeunload", function (event) {
                ws.close();
            });

            // ws.addEventListener('open', function () {
            //     //发送用户上线通知
            //     SendUserOnLine();
            // });

            if (isNull(ws.onopen)) {
                //未成功链接WebSocket就关闭即时通讯列表
                $('#zmain_easyui_layout').layout('remove', 'east');
            } else {

            }
        } else {
            //未启用即时通讯关闭即时通讯列表
            $('#zmain_easyui_layout').layout('remove', 'east');
        }
    }
}